package com.cykj.controller;

import com.alibaba.fastjson.JSON;
import com.cykj.bean.Message;
import com.cykj.bean.TbUser;
import com.cykj.service.UserService;
import com.cykj.utils.RedisUtil;
import com.cykj.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;

    @RequestMapping("/login")
    public Message login(String acc,String pwd){
        Message message = new Message();
        System.out.println(acc+"/"+pwd);
        TbUser user = userService.login(acc,pwd);
        if (user != null){
            message.setData(user);
            String token = TokenUtils.createToken(acc, pwd);
            message.setToken(token);
            message.setCode(200);
            String json = JSON.toJSONString(user);
            redisUtil.set(token,json);
        }else{
            message.setCode(-1);
        }
        return message;
    }


    @RequestMapping("/reg")
    public Message reg(String acc,String pwd,String name){
        Message message = new Message();
        System.out.println(acc+"/"+pwd+"/"+name);
        TbUser user = userService.selectbyAcc(acc);
        if (user == null){
            int i = userService.reg(acc,pwd,name);
            if (i != 0){
                message.setCode(200);
            }
        }else {
            message.setCode(-1);
        }
        return message;
    }
}

